package de.tmahr.android;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import de.tmahr.android.logger.LogActivity;

import android.os.Bundle;
import android.os.Environment;

public class ExternalStorageTest extends LogActivity
{
	public ExternalStorageTest()
	{
		super("ExternalStorageTest");
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		String state = Environment.getExternalStorageState();
		if(!state.equals(Environment.MEDIA_MOUNTED))
		{
			log("Kein externer Speicher verfügbar");
		}
		else
		{
			File dir = Environment.getExternalStorageDirectory();
			log("dir: " + dir.toString());
			
			String path = dir.getAbsolutePath() + File.separator +"text.txt";
			log("path: " + path);
			
			File file = new File(path);
			
			try
			{
				writeTextFile(file,"Dies ist ein Test des externen Speichers");
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				String text = readTextFile(file);
				log("Gelesen: " + text);
				
				if(!file.delete())
				{
					log("Kann Datei " + path + " nicht löschen");
				}				
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}	
	
	private void writeTextFile(File file, String text) throws IOException
	{
		BufferedWriter writer = new BufferedWriter(new FileWriter(file));
		writer.write(text);
		writer.close();
	}
	
	private String readTextFile(File file) throws IOException
	{
		BufferedReader reader = new BufferedReader(new FileReader(file));
		StringBuilder sb = new StringBuilder();
		String line;
		while((line=reader.readLine()) != null)
		{
			sb.append(line);
		}
		return sb.toString();
	}
}


































